import os
from flask import Flask, render_template

from app.extensions import db, login_manager
from app.config import Config

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    
    # 注册蓝图
    from app.views.main import main_bp
    from app.views.auth import auth_bp
    from app.views.text_tools import text_tools_bp
    from app.views.image_tools import image_tools_bp
    from app.views.dev_tools import dev_tools_bp
    from app.views.admin import admin_bp
    from app.views.converter_tools import converter_tools_bp
    from app.views.file_tools import file_tools_bp
    from app.views.life_tools import life_tools_bp
    
    app.register_blueprint(main_bp)
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(text_tools_bp, url_prefix='/tools/text')
    app.register_blueprint(image_tools_bp, url_prefix='/tools/image')
    app.register_blueprint(dev_tools_bp, url_prefix='/tools/dev')
    app.register_blueprint(admin_bp, url_prefix='/admin')
    app.register_blueprint(converter_tools_bp, url_prefix='/tools/converter')
    app.register_blueprint(file_tools_bp, url_prefix='/tools/file')
    app.register_blueprint(life_tools_bp, url_prefix='/tools/life')
    
    # 创建上下文处理器
    @app.context_processor
    def inject_common_data():
        return dict(app_name="工具箱")
    
    # 创建错误处理器
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('errors/404.html'), 404
    
    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('errors/500.html'), 500
    
    return app 